#include<stdio.h>
#include<cv.h>
#include<highgui.h>

void surf(char* filename){
    //コピー
    IplImage *img;
    img=cvLoadImage(filename, CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR);
    IplImage *img2;
    img2=cvCreateImage(cvSize(img->width,img->height),IPL_DEPTH_8U,1);
    cvConvertImage(img,img2,0);
    cvReleaseImage(&img);//←これをしないとメモリーが足りなくなるのかな?
    img=NULL;

    //SURF注目点の抽出
    CvSURFParams params=cvSURFParams(500,1);
    CvMemStorage* storage=cvCreateMemStorage(0);
    CvSeq *keypoints,*descriptors;
    cvExtractSURF(img2,0,&keypoints,&descriptors,storage,params,0);

    int i,j;
    printf("[");
    for(i=0;i<descriptors->total;i++){
        if(i!=0) printf(",");
        CvSURFPoint* keypoint;
        float* descriptor;
        
        keypoint=(CvSURFPoint*)cvGetSeqElem(keypoints,i);
        descriptor=(float*)cvGetSeqElem(descriptors,i);
        //　↑CV_GET_SEQ_ELEMを使うとどういうわけかassertで引っかかってしまうのでNG
        
        printf("{\"point\":[%f,%f,%d,%f,%d],\"descriptor\":[",keypoint->pt.x,keypoint->pt.y,keypoint->size,keypoint->dir,keypoint->laplacian);
        for(j=0;j<127;j++) printf("%f,",descriptor[j]);
        printf("%f]}",descriptor[127]);
    }
    printf("]");

    cvClearSeq(keypoints);cvClearSeq(descriptors);
    cvReleaseMemStorage(&storage);
    cvReleaseImage(&img2);
}

int main(int argc,char** argv){
    if(argc!=2) return 0;
    
    surf(argv[1]);
    return 0;
}
